"""
对话框类，总是处于所有组件的顶部，且无法编辑其余组件
适用于临时获取信息，分为exec阻塞，show非阻塞，modal_show半阻塞
"""

import sys
from typing import Optional
from PySide6.QtWidgets import QApplication, QDialog, QDialogButtonBox, QHBoxLayout, QInputDialog, QLineEdit, QPushButton, QWidget


class DialogWidget(QDialog):
    def __init__(self, parent: Optional[QWidget] = None) -> None:
        super().__init__(parent=parent)
        self.line_editor = QLineEdit(self)
        self.line_editor.setPlaceholderText("modal属性" + str(self.isModal()))
        hbox = QHBoxLayout()
        button_box = QDialogButtonBox(self)
        button_box.addButton(QDialogButtonBox.Ok)
        button_box.addButton(QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        hbox.addWidget(self.line_editor)
        hbox.addWidget(button_box)
        self.setLayout(hbox)

    def get_content(self):
        return self.line_editor.text()


class ParentWidget(QWidget):
    def __init__(self, parent: Optional[QWidget] = None) -> None:
        super().__init__(parent=parent)
        self.__init_subwidget()
        self.__init_layout()
        self.__init_connect()

    def __init_subwidget(self):
        self.__exec_button = QPushButton("打开阻塞对话框")
        self.__show_button = QPushButton("打开非阻塞对话框")
        self.__modal_show_button = QPushButton("打开半阻塞对话框")
        self.__push_int_diaglog = QPushButton("打开获取整数对话框")

    def __init_layout(self):
        hbox = QHBoxLayout()
        hbox.addWidget(self.__exec_button)
        hbox.addWidget(self.__show_button)
        hbox.addWidget(self.__modal_show_button)
        hbox.addWidget(self.__push_int_diaglog)

        self.setLayout(hbox)

    def __init_connect(self):
        self.__exec_button.clicked.connect(self.__slot_exec)
        self.__show_button.clicked.connect(self.__slot_show)
        self.__modal_show_button.clicked.connect(
            self.__slot_modal_show)
        self.__push_int_diaglog.clicked.connect(self.__slot_int_diaglog)

    def __slot_exec(self):
        diaglog = DialogWidget(self)
        if diaglog.exec():       # 需要返回值，会阻塞其他操作，返回值可以为OK或FALSE，对应返回值0或1
            print(diaglog.get_content())

    def __slot_show(self):
        diaglog = DialogWidget(self)
        print(diaglog.show())       # 立即返回None，仍可以操作其他组件

    def __slot_modal_show(self):
        diaglog = DialogWidget(self)
        diaglog.setModal(True)
        print(diaglog.show())       # 立即返回，不能操作其他组件，不会阻塞主进程的processEvent

    def __slot_int_diaglog(self):
        int_dialog, valid = QInputDialog.getInt(
            self, "获取整数", "请输入一个整数", 1, 0, 100, 5)
        if valid:   # 点击取消会返回数字+False
            print(int_dialog)       # 数字+True


if __name__ == "__main__":
    # 主流程控制，一个程序只能有一个QApplication，sys可以用于命令行导入
    app = QApplication(sys.argv)
    window = ParentWidget()
    window.show()
    sys.exit(app.exec())               # 控制程序安全退出
